<template>
  <el-dialog title="工序权限配置" append-to-body :visible.sync="visible" @close="handleClose">
    <div style="height: 500px; overflow-x: hidden">
      <el-tree ref="elTree" :data="data" :props="props" node-key="id" show-checkbox :default-checked-keys="defaultChecked" :default-expand-all="true" @check="currentCheck" />
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button size="small" type="primary" @click="submit"><i class="el-icon-circle-check"></i><span>保 存</span></el-button>
      <el-button size="small" @click="handleClose"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getWorkStationAll, userWorkStationSubmit, getUserWorkStationDetail } from '@/api/system/user';
export default {
  name: 'workingProcedureModal',
  props: ['visible', 'userRow'],
  data() {
    return {
      data: [],
      props: {
        label: 'name',
        children: 'children'
      },
      defaultChecked: [],
      selectData: []
    };
  },
  watch: {
    visible: function () {
      if (this.visible) {
        getWorkStationAll().then((res) => {
          let data = this._get(res, 'data.data', []);
          let arrs = [];
          for (let key in data) {
            arrs.push(key);
          }
          console.log(arrs);
          this.data = [];
          this._forEach(arrs, (item, index) => {
            this.data.push({
              id: index,
              name: item,
              children: data[item]
            });
          });
        });
        getUserWorkStationDetail(this.userRow.id).then((res) => {
          this.defaultChecked = this._map(res.data.data, (item) => {
            return item.workstationId;
          });
        });
      }
    }
  },
  methods: {
    currentCheck(data, node) {
      console.log(data, node);
      let selectData = node.checkedNodes;
      this.selectData = this._map(selectData, (item) => {
        return {
          workstationId: item.id,
          workstationCode: item.code,
          workstationName: item.name
        };
      });
    },
    submit() {
      userWorkStationSubmit(this.userRow.id, this.userRow.name, this.selectData).then((res) => {
        this.$message.success(res.data.msg);
        this.handleClose();
      });
    },
    // 事件
    handleClose() {
      this.$refs.elTree.setCheckedKeys([]);
      this.defaultChecked = [];
      this.$emit('update:visible', false);
    }
  }
};
</script>
